package vn.com.shoppie.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import vn.com.shoppie.network.WiModelManager;
import vn.com.shoppie.setting.SettingPreference;
import vn.com.shoppie.sobject.LinkPost;
import vn.com.shoppie.sobject.ShoppieObject;
import vn.com.shoppie.sobject.User;
import vn.com.shoppie.sobjmng.LinkMng;
import vn.com.shoppie.sobjmng.UserMng;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.database.SQLException;
import android.util.Log;

public class SUtilXml {
	private static SUtilXml _instance = new SUtilXml();

	public static SUtilXml getInstance() {
		return _instance;
	}
	// 24*60*60*1000
	long thresoldGET = 41600000;
	long thresoldPOST = 41600000;

	public String getXmlFromLink(Context context, String link) throws ClientProtocolException, IOException {
		LinkMng linkMng = new LinkMng(context);
		ArrayList<LinkPost> array = linkMng.select(LinkMng.link, link);
		if (array != null && array.size() > 0) {
			LinkPost linkPost = array.get(0);
			long crtTime = System.currentTimeMillis();
			long linkTime = linkPost.time;
			if ((crtTime - linkTime) <= thresoldGET) {
				return linkPost.xml;
			}
			linkMng.delete(linkPost._id);
		}
		String xml = getXmlFromUrl(link);
		if (xml != null && xml.length() > 0) {
			LinkPost newLinkPost = new LinkPost(-1, link, xml, System.currentTimeMillis() + "");
			linkMng.insertNewTo(newLinkPost.getValues());
		}
		return xml;
	}

	public String postXml(Context context, String link, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IllegalArgumentException, IOException {
		return postXml(context, link, nameValuePairs, thresoldPOST);
	}

	public String postXml(Context context, String link, List<NameValuePair> nameValuePairs, long threasoldPOST) throws ClientProtocolException, IllegalArgumentException, IOException {
		String encodeLink = link + "?";
		for (NameValuePair item : nameValuePairs) {
			encodeLink += item.getName() + "=" + item.getValue() + "&";
		}
		LinkMng linkMng = new LinkMng(context);
		ArrayList<LinkPost> array = linkMng.select(LinkMng.link, encodeLink);
		if (array != null && array.size() > 0) {
			LinkPost linkPost = array.get(0);
			long crtTime = System.currentTimeMillis();
			long linkTime = linkPost.time;
			if ((crtTime - linkTime) <= threasoldPOST) {
				return linkPost.xml;
			}
			linkMng.delete(linkPost._id);
		}
		String xml = sendPost(link, nameValuePairs);
		if (xml != null && xml.length() > 0) {
			LinkPost newLinkPost = new LinkPost(-1, encodeLink, xml, System.currentTimeMillis() + "");
			linkMng.insertNewTo(newLinkPost.getValues());
		}
		return xml;
	}

	private String sendPost(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException, IllegalArgumentException {
		HttpClient httpclient = new DefaultHttpClient();
		// Your URL String
		// url="http://ws.shoppie.com.vn/index.php/api/webservice/autoregister";
		HttpPost httppost = new HttpPost(url);

		// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		// nameValuePairs.add(new BasicNameValuePair("deviceToken",
		// util.getDeviceId(BluetoothExample.this)));
		// nameValuePairs.add(new BasicNameValuePair("deviceType", "Android"));
		// nameValuePairs.add(new BasicNameValuePair("custCode", address));

		// if(nameValuePairs.size()>0)
		httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		HttpResponse response;
		response = httpclient.execute(httppost);
		HttpEntity responseEntity = response.getEntity();
		if (responseEntity != null) {
			String xml;
			// xml= EntityUtils.toString(responseEntity);
			xml = EntityUtils.toString(responseEntity, "UTF-8");
			// System.out.println(xml);
			return xml;
		}
		return null;
	}

	private String getXmlFromUrl(String url) throws ClientProtocolException, IOException {
		// String url =
		// "http://ws.shoppie.com.vn/index.php/api/webservice/merchcampaigns";
		// url merchant:
		// http://ws.shoppie.com.vn/index.php/api/webservice/merchants
		XMLParser pa = new XMLParser();
		try {
			String value = pa.getXmlFromUrl(url);
			if (!value.contains("error")) {
				// System.out.println("XMLParse: "+value);
				return value;
			}
		} catch (NullPointerException e) {
			Log.i("SUtilXML line 130", e.toString());
		}
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromHttpResponse(response);
		// System.out.println("XMLParse from HTML response:"+xml);
		return xml;
	}

	public int registerAccount(Context context) {
		SUtil util = SUtil.getInstance();
		util.configBluetooth(true);
		String address = "";
		try {
			address = BluetoothAdapter.getDefaultAdapter().getAddress();
		} catch (NullPointerException e) {
			return -1;
		}
		util.configBluetooth(false);
		if (address == null) {
			Log.e("address", "null");
			return -1;
		}
		return registerAccount(context, util.getDeviceId(context), address);
	}

	/**
	 * @warning: must be run in non-UI thread.
	 * */
	public int registerAccount(Context context, String deviceId, String bluetoothId) {
		int userID = -1;
		// send POST
		String url = SConfig.URL_SHOPPIE_HOME + SConfig.URL_REGISTER;

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("deviceToken", /*
																 * util.getDeviceId
																 * (context)
																 */deviceId));
		nameValuePairs.add(new BasicNameValuePair("deviceType", "Android"));
		nameValuePairs.add(new BasicNameValuePair("custCode", bluetoothId));
		try {
			String xml = SUtilXml.getInstance().postXml(context, url, nameValuePairs, 200);
			WiModelManager mng = new WiModelManager();
			ArrayList<ShoppieObject> data = new ArrayList<ShoppieObject>();
			mng.parse(xml);
			data = mng.getResultShoppieObject();
			// System.out.println(data.size() + "");
			// for (ShoppieObject user : data) {
			// System.out.println(((User) user).id);
			// }

			try {
				User user = new User(-1, ((User) data.get(0)).custId, "");
				try {
					userID = Integer.valueOf(((User) data.get(0)).custId);
				} catch (NumberFormatException e) {
					return -1;
				}
				SettingPreference.setUserID(context, Integer.valueOf(((User) data.get(0)).custId));
				System.out.println("User ID:" + ((User) data.get(0)).custId);
				new UserMng(context).insertNewTo(user.getValues());
				return userID;
			} catch (SQLException e) {
				System.out.println(e.toString());
				return userID;
			}
		} catch (ClientProtocolException e) {
			System.out.println(e.toString());
			return userID;
		} catch (IOException e) {
			System.out.println(e.toString());
			return userID;
		}
	}
}
